//
//  CheckCarViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/11/9.
//  Copyright © 2018 changqingkeji. All rights reserved.
//

import UIKit
import WebKit
import JavaScriptCore
import SnapKit

class CheckCarViewController: UIViewController {

    @IBOutlet weak var carView: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var photoCountLabel: UILabel!
    @IBOutlet weak var submitButton: UIButton!
    
    @IBOutlet weak var checkCarInstructionLabel: UILabel!
    
    struct Image {
        let section: String
        let path: String
        let image: UIImage
    }
    
    var data = [Image]() {
        didSet {
            collectionView.reloadData()
            photoCountLabel.text = "(\(data.count)/18)"
            submitButton.setTitle(data.count == 0 ? "外观无伤，跳过" : "外观有伤，提交", for: .normal)
        }
    }
    
    var webView: WKWebView!
    
    var selectedSection: String? = nil
    
    var orderId: String!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        checkCarInstructionLabel.text = slipViewController?.config?.checkCarInstruction
        
        let config = WKWebViewConfiguration()
        config.preferences = WKPreferences()
        config.preferences.javaScriptEnabled = true
        config.preferences.javaScriptCanOpenWindowsAutomatically = false
        config.userContentController = WKUserContentController()
        config.processPool = WKProcessPool()
        
        webView = WKWebView(frame: carView.bounds, configuration: config)
        webView.navigationDelegate = self
        
        carView.addSubview(webView)
        
        webView.snp.makeConstraints { make in
            make.top.equalTo(44)
            make.bottom.left.right.equalTo(0)
        }
        
        loadSvg()
        
        config.userContentController.add(self, name: "clickName")
    }
    
    func loadSvg() {
        let p = Bundle.main.path(forResource: "car", ofType: "html")!
        let url = URL(fileURLWithPath: p)
        let request = URLRequest(url: url)
        
        webView.load(request)
    }
    
    @IBAction func closeCarView(_ sender: UIButton) {
        carView.isHidden = true
    }
    
    @IBAction func removeItem(_ sender: UIButton) {
        guard let cell = sender.superview?.superview as? CheckCarCell else {
            return
        }
        
        guard let indexPath = collectionView.indexPath(for: cell) else {
            return
        }
        
        data.remove(at: indexPath.row)
    }
    
    @IBAction func submit(_ sender: UIButton) {
        if data.count == 0 {
            performSegue(withIdentifier: "preorderSegue", sender: nil)
        } else {
            var images = [String: String]()
            for i in data {
                images[i.section] = i.path
            }
            
            JZLoading.showLoadingWith(toView: self.view)
            Order.checkCar(orderId: orderId, checkImage: images, success: { [weak self] in
                JZLoading.hideLoading()
                self?.performSegue(withIdentifier: "preorderSegue", sender: nil)
            }) { [weak self] message in
                JZLoading.hideLoading()
                self?.showError(message)
            }
        }
    }
    
    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "preorderSegue" {
            if let vc = segue.destination as? PreorderViewController {
                vc.isCheckCar = true
                vc.orderId = orderId
            }
        }
    }
}

extension CheckCarViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count == 18 ? 18 : data.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        
        if let cell = cell as? CheckCarCell {
            cell.closeButton.isHidden = false
            if indexPath.row == data.count {
                cell.closeButton.isHidden = true
                cell.image.image = UIImage(named: "add_photo")
            } else {
                let item = data[indexPath.row]
                cell.image.image = item.image
            }
        }
        
        return cell
    }
}

extension CheckCarViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        loadSvg()
        
        carView.isHidden = false
    }
}

extension CheckCarViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        data.forEach { i in
            webView.evaluateJavaScript("remove('\(i.section)')")
        }
    }
}

extension CheckCarViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        if let s = message.body as? String {
            selectedSection = s
        }
        
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let  cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
            cameraPicker.allowsEditing = true
            cameraPicker.sourceType = .camera
            
            present(cameraPicker, animated: true, completion: nil)
        } else {
            showError("不支持拍照")
        }
    }
}

extension CheckCarViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image = info[UIImagePickerControllerEditedImage] as! UIImage
        
        //上传图片
        if let s = selectedSection {
            User.uploadFile(image) { [weak self] path in
                let item = Image(section: s, path: path, image: image)
                self?.data.append(item)
                self?.carView.isHidden = true
            }
        }
        
        dismiss(animated: true, completion: nil)
    }
}
